package com.dinadi.yidi.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dinadi.yidi.R;
import com.dinadi.yidi.adapter.ReplyListAdapter;
import com.dinadi.yidi.base.BaseActivity;
import com.dinadi.yidi.bean.ReplyListBean;
import com.dinadi.yidi.bean.ReplyListRequest;
import com.dinadi.yidi.bean.ReplyListRequestEntity;
import com.dinadi.yidi.bean.WriteCommentsBean;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.ui.MyApplication;
import com.dinadi.yidi.ui.view.CommonDialogUtils;
import com.dinadi.yidi.ui.view.ReplyListViewHead;
import com.dinadi.yidi.utils.ImageUtils;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.SharePreferencesHelper;
import com.dinadi.yidi.utils.UtilPopupWindow;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * author: JiaYu.He
 * Date: 2017/4/12   回复列表
 * Time: 15:06
 */

public class ReplyListActivity extends BaseActivity {
    private View view;
    private TextView tvTitle, tv_more;
    private CircleImageView head_img;
    private TextView designer_nick_name, creat_time, content;
    private ImageView goto_comment;
    private ReplyListViewHead customListView;
    private ProgressBar pbLoad;
    private ReplyListAdapter adapter;
    private List<ReplyListRequestEntity> mList = new ArrayList<>();
    private Handler handler = new Handler();
    private int page = 1;
    private int itemIndex;
    private String commentId, toUserId;
    private String userID,token;

    @Override
    protected View getLayout() {
        view = LayoutInflater.from(ReplyListActivity.this).inflate(R.layout.activity_reply_list, null);
        return view;
    }

    @Override
    protected void noWifiRefresh() {

    }

    @Override
    protected void initView() {
        changePager(2);
        tvTitle = (TextView) view.findViewById(R.id.text_title);
        tvTitle.setText(getResources().getString(R.string.text_reply_list));
        customListView = (ReplyListViewHead) view.findViewById(R.id.custom_listview);
        tv_more = (TextView) view.findViewById(R.id.tvLoadText);
        customListView.setDivider(null);
        pbLoad = (ProgressBar) view.findViewById(R.id.pbLoad);
        adapter = new ReplyListAdapter(ReplyListActivity.this, mList);
        customListView.setAdapter(adapter);
        designer_nick_name = (TextView) view.findViewById(R.id.designer_nick_name);
        creat_time = (TextView) view.findViewById(R.id.creat_time);
        content = (TextView) view.findViewById(R.id.content);
        head_img = (CircleImageView) view.findViewById(R.id.head_img);
        goto_comment = (ImageView) view.findViewById(R.id.goto_comment);
    }


    @Override
    protected void initData() {
        token = SharePreferencesHelper.getInstance(ReplyListActivity.this).getString("token");
        userID = MyApplication.getApp().getUser().getUserId();
        Intent intent = getIntent();
        commentId = intent.getStringExtra("commentId");
        toUserId = intent.getStringExtra("toUserId");
        String imgUrl = intent.getStringExtra("imgUrl");
        String contents = intent.getStringExtra("content");
        String nickName = intent.getStringExtra("nickName");
        String creatTime = intent.getStringExtra("creatTime");
        designer_nick_name.setText(nickName);
        creat_time.setText(creatTime);
        try {
            contents = URLDecoder.decode(contents, "utf-8");
//            str = URLDecoder.decode(str,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        content.setText(contents);
        if (imgUrl == null) {
            ImageUtils.loadImageView(ReplyListActivity.this, R.drawable.me_img_default, head_img);
        } else {
            if (!imgUrl.equals("")) {
                ImageUtils.loadImageView(ReplyListActivity.this, imgUrl, head_img);
            } else {
                ImageUtils.loadImageView(ReplyListActivity.this, R.drawable.me_img_default, head_img);
            }
        }
        ReplyListBean bean = new ReplyListBean();
        bean.setCommentId(commentId);
        bean.setPageNum("1");
        bean.setPageSize("20");
        CommonInterface replyListInterface = new CommonInterface(ReplyListActivity.this, httpListener);
        replyListInterface.getInterface("15000", JSON.toJSONString(bean));
    }

    @Override
    protected void initListener() {
        /**关键在这里，listview滑动监听方法*/
        customListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                int lastIndex = adapter.getCount() - 1;
                int item = lastIndex + 2;
                Log.d("TAG", "滑动的Item" + item);
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && itemIndex == item) {
                    loadData();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                itemIndex = firstVisibleItem + visibleItemCount - 1;
                Log.d("TAG", "滑动" + itemIndex);
            }
        });
        registerClickListener(goto_comment);
    }

    @Override
    protected void clickEvent(View v) {
        switch (v.getId()) {
            case R.id.goto_comment:
                showEditPopup();
                break;
            default:
                break;
        }

    }

    private void loadData() {
        tv_more.setText("正在加载...");
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                tv_more.setText("上拉加载");
                page = page + 1;
                initPullrefresh();
            }
        }, 2000);

    }

    private void initPullrefresh() {
        ReplyListBean bean = new ReplyListBean();
        bean.setCommentId(commentId);
        bean.setPageNum(page + "");
        bean.setPageSize("20");
        CommonInterface replyListInterface = new CommonInterface(ReplyListActivity.this, httpListener);
        replyListInterface.getInterface("15000", JSON.toJSONString(bean));
    }

    /*评论的弹kuang*/
    private void showEditPopup() {
        //当然是先初始化popupWindow
        final UtilPopupWindow popupWindow = new UtilPopupWindow();
        //我再工具中没有写构造函数，这里调用默认的构造函数
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        final int windowHeight = d.getHeight();
        //弹出框填充布局
        LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_comment, null);
        RelativeLayout layout2 = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_reply_list, null);
        popupWindow.setPopupWindow(ReplyListActivity.this, windowHeight / 4, layout, layout2, Gravity.BOTTOM);
        TextView canel = (TextView) layout.findViewById(R.id.canel);
        TextView release = (TextView) layout.findViewById(R.id.release);
        final EditText edit_comment = (EditText) layout.findViewById(R.id.edit_comment);
        canel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
           /*自动弹出键盘*/
        edit_comment.setFocusableInTouchMode(true);
        edit_comment.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) edit_comment.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(edit_comment, 0);
                           }

                       },
                100);
        release.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                String content = edit_comment.getText().toString();
                String content = null;
                try {
                    content = URLEncoder.encode(edit_comment.getText().toString(), "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                if (content.length() < 1) {
                    toast("内容不能为空哦");
                } else {
                    WriteCommentsBean bean = new WriteCommentsBean();
                    bean.setTargetId(commentId);
                    bean.setFromUserId(userID);
                    bean.setToUserId(toUserId);
                    bean.setContent(content);
                    bean.setType("2");
                    bean.setToken(token);
                    CommonInterface writeCommentsInterface = new CommonInterface(ReplyListActivity.this, httpListener4);
                    writeCommentsInterface.getInterface("15002", JSON.toJSONString(bean));
                    popupWindow.dismiss();

                }

            }
        });
    }

    HttpListener httpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            mList.clear();
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            if (errCode.equals("0000")) {
                ReplyListRequest replyListRequest = JsonUtil.parseJsonToBean(response, ReplyListRequest.class);
                //   mList = commentList.getCommentList();

                if (replyListRequest.getReplyList().size() == 0) {

                    tv_more.setText("已显示全部评论");
                    tv_more.setTextColor(getResources().getColor(R.color.color_999999));
                    pbLoad.setVisibility(View.GONE);

                } else if (replyListRequest.getReplyList().size() < 20) {

                    tv_more.setText("已显示全部评论");
                    tv_more.setTextColor(getResources().getColor(R.color.color_999999));
                    pbLoad.setVisibility(View.GONE);

                }


                mList.addAll(replyListRequest.getReplyList());
                adapter.notifyDataSetChanged();

            } else {
                toast("获取信息失败");
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
        }
    };

    /*写评论*/
    HttpListener httpListener4 = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                toast("评论成功");
                mList.clear();
                initPullrefresh();
            }
        }


        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            toast("发表失败");
        }

    };
}
